package org.jeecg.modules.demo.mp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.mp.entity.MpBgUpload;
import org.jeecg.modules.demo.mp.entity.MpPeriod;
import org.jeecg.modules.demo.mp.service.IMpBgUploadService;
import org.jeecg.modules.demo.mp.service.IMpPeriodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: Period
 * @Author: jeecg-boot
 * @Date: 2022-06-28
 * @Version: V1.0
 */
@Api(tags = "Period")
@RestController
@RequestMapping("/mp/mpPeriod")
@Slf4j
public class MpPeriodController extends JeecgController<MpPeriod, IMpPeriodService> {
    @Autowired
    private IMpPeriodService mpPeriodService;
    @Autowired
    private IMpBgUploadService mpBgUploadService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 分页列表查询
     *
     * @param mpPeriod
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "Period-分页列表查询")
    @ApiOperation(value = "Period-分页列表查询", notes = "Period-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MpPeriod>> queryPageList(MpPeriod mpPeriod,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        QueryWrapper<MpPeriod> queryWrapper = QueryGenerator.initQueryWrapper(mpPeriod, req.getParameterMap());

        Page<MpPeriod> page = new Page<MpPeriod>(pageNo, pageSize);
        IPage<MpPeriod> pageList = mpPeriodService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mpPeriod
     * @return
     */
    @AutoLog(value = "Period-添加")
    @ApiOperation(value = "Period-添加", notes = "Period-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MpPeriod mpPeriod) {
        mpPeriodService.save(mpPeriod);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mpPeriod
     * @return
     */
    @AutoLog(value = "Period-编辑")
    @ApiOperation(value = "Period-编辑", notes = "Period-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MpPeriod mpPeriod) {
        mpPeriodService.updateById(mpPeriod);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "Period-通过id删除")
    @ApiOperation(value = "Period-通过id删除", notes = "Period-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mpPeriodService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "Period-批量删除")
    @ApiOperation(value = "Period-批量删除", notes = "Period-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mpPeriodService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "Period-通过id查询")
    @ApiOperation(value = "Period-通过id查询", notes = "Period-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MpPeriod> queryById(@RequestParam(name = "id", required = true) String id) {
        MpPeriod mpPeriod = mpPeriodService.getById(id);
        if (mpPeriod == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mpPeriod);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mpPeriod
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MpPeriod mpPeriod) {
        return super.exportXls(request, mpPeriod, MpPeriod.class, "Period");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MpPeriod.class);
    }

    /**
     * 设置为工作版本
     *
     * @param mpPeriod
     * @return
     */
    @AutoLog(value = "工作版本-设置当前版本")
    @RequestMapping(value = "/setCurrent", method = RequestMethod.POST)
    public Result<Boolean> setCurrent(MpPeriod mpPeriod) {
        Result<Boolean> result = new Result<>();
        result.setResult(true);
        String id = mpPeriod.getId();
//		 log.info("--设置工作版本---id:" + id);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(false);
            result.setMessage("ID不能为空");
            return result;
        }

        // 更新为工作状态
        MpPeriod dbPeriod = mpPeriodService.getById(id);
        if ("Budget".equalsIgnoreCase(dbPeriod.getTyp())) {

//  TODO  根据Type生成对应的版本的上传信息
            String sql = "SELECT division FROM mp_division";
            List<String> divisionList = jdbcTemplate.queryForList(sql, String.class);
//        List<Map> divisionList = JdbcUtil.executeQuery(jdbcTemplate, sql, null);
            if (!divisionList.isEmpty()) {
                QueryWrapper<MpBgUpload> checkWrapper;
                MpBgUpload upload;
                for (String division : divisionList) {
                    //  判断版本是否存在，不存在则新增
                    checkWrapper = new QueryWrapper<MpBgUpload>();
                    checkWrapper.eq("division", division);
                    checkWrapper.eq("version", dbPeriod.getVersion());
                    if (!mpBgUploadService.getBaseMapper().exists(checkWrapper)) {
                        upload = new MpBgUpload();
                        upload.setVersion(dbPeriod.getVersion());
                        upload.setDivision(division);
                        mpBgUploadService.save(upload);
                    }
                }
            }


            // 已有记录更新成非工作状态
            QueryWrapper<MpPeriod> queryWrapper = new QueryWrapper<MpPeriod>();
            queryWrapper.eq("iscurrent", 1);
            queryWrapper.eq("typ", dbPeriod.getTyp());
            List<MpPeriod> list = mpPeriodService.list(queryWrapper);
            for (MpPeriod versionCtrl2 : list) {
                versionCtrl2.setIscurrent(0);
                mpPeriodService.saveOrUpdate(versionCtrl2);
            }

//        更新为当前版本
            dbPeriod.setIscurrent(1);
            mpPeriodService.saveOrUpdate(dbPeriod);
        }
        result.setSuccess(true);
        result.setMessage("工作版本切换成功");

        return result;
    }


}
